package com.wlcorp.forcazamis.business.baseinfo.impl;

import java.util.List;

import com.wlcorp.forcazamis.business.baseinfo.IDepotService;
import com.wlcorp.forcazamis.dao.baseinfo.IDepotDAO;
import com.wlcorp.forcazamis.dao.sample.ISubSampleAssignDAO;
import com.wlcorp.forcazamis.dao.system.IStaffDAO;
import com.wlcorp.forcazamis.domain.baseinfo.Depot;
import com.wlcorp.forcazamis.domain.sample.SubSampleAssign;
import com.wlcorp.forcazamis.domain.system.Staff;
import com.wlcorp.forcazamis.exception.ServiceException;
import com.wlcorp.forcazamis.sys.BaseService;
import com.wlcorp.forcazamis.sys.util.AppConstant;

public class DepotServiceImpl extends BaseService implements IDepotService {
	
	private IDepotDAO depotDAO;
	private IStaffDAO staffDAO;
	private ISubSampleAssignDAO subSampleAssignDAO;
	
	public void setDepotDAO(IDepotDAO depotDAO) {
		this.depotDAO = depotDAO;
	}
	
	public void setStaffDAO(IStaffDAO staffDAO) {
		this.staffDAO = staffDAO;
	}

	public void setSubSampleAssignDAO(ISubSampleAssignDAO subSampleAssignDAO) {
		this.subSampleAssignDAO = subSampleAssignDAO;
	}

	public List<Depot> getDepotList(Depot depot) throws ServiceException {
		return depotDAO.getDepotList(depot);
	}

	public Depot getDepotById(Long depotId) throws ServiceException {
		if(null == depotId){
			return null;
		}
		return depotDAO.getDepotById(depotId);
	}

	public void saveDepot(Depot depot) throws ServiceException {
		//如果更新中修改仓库为无效，则必须判断该仓库是否有库存
		if(null != depot.getDepotId() && null != depot.getFlag() && AppConstant.DEPOT_NOT_INACTIVE == depot.getFlag()){
			SubSampleAssign subSampleAssign = new SubSampleAssign();
			subSampleAssign.setOwnerId(depot.getDepotId());
			subSampleAssign = subSampleAssignDAO.getSubSampleAssignBySubSampleAndOwner(subSampleAssign);
			if(null != subSampleAssign && subSampleAssign.getSampleCount() > 0){
				setErrorField(depot,AppConstant.BASE_BEAN_STATUS_ERROR,"仓库已有库存样品，不能设为无效！");
				return;
			}
		}
		if(null != depot.getManagerId()){
			depot.setManager(staffDAO.getStaffById(depot.getManagerId()));
		}
		
		depotDAO.saveDepot(depot);
	}

	public void deleteDepot(Depot depot) throws ServiceException {
		if(AppConstant.DEPOT_ID_SAMPLE == depot.getDepotId()){
			setErrorField(depot,AppConstant.BASE_BEAN_STATUS_ERROR,"样品库不能删除!");
			return;
		}
		Staff staff = new Staff();
		staff.setDepotId(depot.getDepotId());
		Long count = staffDAO.getStaffCount(staff);
		if(count > 0){
			setErrorField(depot,AppConstant.BASE_BEAN_STATUS_ERROR,"仓库已使用,无法删除!");
			return;
		}
		depotDAO.deleteDepot(depot);
	}
}
